package priv.pfz.basedao.apt;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Map;

/**
 * @author yyjxp
 * 2024/1/28 19:08
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class AptUtils {
    /**
     * 表字段名转java字段名
     * create_time -> createTime
     */
    public static String columnToField(String column) {
        StringBuilder sb = new StringBuilder();
        boolean nextUpper = false;
        for (int i = 0; i < column.length(); i++) {
            char c = column.charAt(i);
            if (c == '_') {
                nextUpper = true;
            } else if (nextUpper) {
                sb.append(Character.toUpperCase(c));
                nextUpper = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * java字段名转表字段名
     * createTime -> create_time
     */
    public static String fieldToColumn(String field) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < field.length(); i++) {
            char c = field.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append("_").append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 表名转java类名
     * trade_info -> TradeInfo
     */
    public static String tableToClass(String table) {
        StringBuilder sb = new StringBuilder();
        boolean nextUpper = false;
        sb.append(Character.toUpperCase(table.charAt(0)));
        for (int i = 1; i < table.length(); i++) {
            char c = table.charAt(i);
            if (c == '_') {
                nextUpper = true;
            } else if (nextUpper) {
                sb.append(Character.toUpperCase(c));
                nextUpper = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * java类名转表名
     * TradeInfo -> trade_info
     */
    public static String classToTable(String clazz) {
        StringBuilder sb = new StringBuilder();
        sb.append(Character.toLowerCase(clazz.charAt(0)));
        for (int i = 1; i < clazz.length(); i++) {
            char c = clazz.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append("_").append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static String fillTemplate(String template, Map<String, String> params) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            template = template.replaceAll("\\$\\{" + entry.getKey() + "\\}", entry.getValue());
        }
        return template;
    }
}
